package com.jingdun.sport.pay

import com.alipay.api.AlipayApiException
import com.alipay.api.AlipayClient
import com.alipay.api.DefaultAlipayClient
import com.alipay.api.domain.AlipayTradeAppPayModel
import com.alipay.api.request.AlipayTradeAppPayRequest
import lombok.Data
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.PropertySource
import org.springframework.stereotype.Component
import org.springframework.stereotype.Service

@Data
@Component
@PropertySource("classpath:alipay.properties")
@ConfigurationProperties(prefix = "alipay")
class Alipay {
    // 商户ID
    var appid: String? = null

    // 私钥
    var rsa_private_key: String? = null

    // 异步回调地址
    var notify_url: String? = null

    // 同步回调地址
    var return_url: String? = null

    // 请求网关地址
    var gateway_url: String? = null

    // 编码
    var charset: String? = null

    // 返回格式
    var format: String? = null

    // 支付宝公钥
    var alipay_public_key: String? = null

    // RSA2
    var signtype: String? = null
}

class Bill {
    var subject: String? = null
    var tradeNo: String? = null
    var amount: Long = 0
    var amountScale = 100
}

@Service
class PayService {
    @Autowired
    private lateinit var alipay: Alipay

    fun pay(bill: Bill): String {
        //实例化客户端

        //实例化客户端
        val alipayClient: AlipayClient = DefaultAlipayClient(alipay.gateway_url, alipay.appid, alipay.rsa_private_key,
                alipay.format, alipay.charset, alipay.alipay_public_key, alipay.signtype)
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        val request = AlipayTradeAppPayRequest()
//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        val model = AlipayTradeAppPayModel()
        model.subject = bill.subject
        model.outTradeNo = bill.tradeNo
        model.timeoutExpress = "15m"
        model.totalAmount = "${bill.amount / bill.amountScale}.${String.format("%02d", bill.amount % bill.amountScale)}"
        model.productCode = bill.tradeNo
        model.passbackParams = ""
        model.productCode = "QUICK_MSECURITY_PAY" //销售产品码，固定为QUICK_MSECURITY_PAY

        request.bizModel = model
        request.notifyUrl = alipay.notify_url
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            val response = alipayClient.sdkExecute(request)
            println(response.body) //就是orderString 可以直接给客户端请求，无需再做处理。
            return response.body
        } catch (e: AlipayApiException) {
            e.printStackTrace()
            throw e
        }
    }
}